import api from './api';
import wxApi from './wxApi';
import keys from './keys';
const wxAuth = {
    login : function(){
        //微信的登录接口
        return new Promise((resolve,reject)=>{
            mpvue.login({
                success : res=>{
                    if(res.code){
                        resolve(res.code);
                    }else{
                        reject(res);
                    }
                },
                fail : error=>{
                    reject(error);
                }
            });
        });
    },
    checkSession : function(){
        // let that = this;
        //检查登录态是否过期
        mpvue.checkSession({
            success : () =>{
                //检查登录态成功
            },
            fail : async ()=>{
                //移除登录授权信息
                mpvue.removeStorageSync(keys.Authorization);
                //调用登录api，请求会被拦截器拦截
                await api.login();
            }
        });
    },
    /**
     * 授权
     */
    authorize : scope => {
        return new Promise(async (resolve,reject)=>{
            if(!keys.Scopes[scope]){
                reject();
            }
            var settings = await wxApi.getSetting();
            if(settings && settings[scope]){
                resolve(scope);
            }else {
                mpvue.authorize({
                    scope : scope,
                    success:()=>{
                        resolve(scope);    
                    },
                    fail : (err)=>{
                        reject(err);
                    }
                })
            }
        });
    }
};
export default wxAuth;